//
//  BaiduGeocodeSearchManager.m
//  YuanXinBaiduMap
//
//  Created by 晏德智 on 16/10/9.
//  Copyright © 2016年 晏德智. All rights reserved.
//

#import "MapSearchService.h"
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import "SearchRequest.h"
#import "RCTConvert+MapSearch.h"

@interface MapSearchService()<BMKGeoCodeSearchDelegate,BMKPoiSearchDelegate>

@property (nonatomic,strong) NSMutableDictionary* resultCache;

@end

@implementation MapSearchService

@synthesize bridge = _bridge;
@synthesize resultCache  = _resultCache;

RCT_EXPORT_MODULE();

- (instancetype)init{
    self = [super init];
    if(self){
        _resultCache =[NSMutableDictionary new];
    }
    return  self;
}


- (void)dealloc{
    [_resultCache removeAllObjects];
    _resultCache =nil;
}

//根据地址名称获取地理信息
RCT_EXPORT_METHOD(geoCode:(BMKGeoCodeSearchOption *)options resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
    BMKGeoCodeSearch *geocodesearch = [BMKGeoCodeSearch new];
    geocodesearch.delegate = self;
    BOOL flag = [geocodesearch geoCode:options];
    if(flag)
    {
        SearchRequest *searchRequest = [SearchRequest new];
        searchRequest.searchOption = options;
        searchRequest.successBlock = resolve;
        searchRequest.errorBlock = reject;
        [self.resultCache setObject:searchRequest forKey:@(geocodesearch.hash)];
        NSLog(@"反geo检索发送成功");
    }
    else
    {
        geocodesearch.delegate =nil;
        geocodesearch =nil;
        reject(@"-1",@"获取地理信息失败",nil);
    }
}

//根据查询信息返回经纬度
RCT_EXPORT_METHOD(reverseGeoCode:(BMKReverseGeoCodeSearchOption *)options resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
    
    BMKGeoCodeSearch *geocodesearch = [BMKGeoCodeSearch new];
    geocodesearch.delegate =self;
    BOOL flag = [geocodesearch reverseGeoCode:options];
    if(flag)
    {
        SearchRequest *searchRequest = [SearchRequest new];
        searchRequest.searchOption = options;
        searchRequest.successBlock = resolve;
        searchRequest.errorBlock = reject;
        //[self.resultCache a
        [self.resultCache setObject:searchRequest forKey:@(geocodesearch.hash)];
        NSLog(@"反geo检索发送成功");
    }
    else
    {
        geocodesearch.delegate =nil;
        geocodesearch =nil;
        reject(@"-1",@"获取经纬度失败",nil);
    }
}

//POI搜索功能
RCT_EXPORT_METHOD(poiSearchInCity:(BMKPOICitySearchOption *)options resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
    
    if(options){
        BMKPoiSearch *poiSearch = [BMKPoiSearch new];
        poiSearch.delegate =self;
        BOOL flag = [poiSearch poiSearchInCity:options];
        
        if(flag)
        {
            SearchRequest *searchRequest = [SearchRequest new];
            searchRequest.searchOption = options;
            searchRequest.successBlock = resolve;
            searchRequest.errorBlock = reject;
            [self.resultCache setObject:searchRequest forKey:@(poiSearch.hash)];
            NSLog(@"反geo检索发送成功");
        }
        else
        {
            poiSearch.delegate =nil;
            poiSearch =nil;
            reject(@"-1",@"获取经纬度失败",nil);
        }
    }else{
        reject(@"-2",@"传入参数有误",nil);
    }
}

//POI搜索功能 矩形云检索参数信息类
RCT_EXPORT_METHOD(poiSearchInbounds:(BMKPOIBoundSearchOption *)options resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
    
    if(options){
        BMKPoiSearch *poiSearch = [BMKPoiSearch new];
        poiSearch.delegate =self;
        BOOL flag = [poiSearch poiSearchInbounds:options];
        
        if(flag)
        {
            SearchRequest *searchRequest = [SearchRequest new];
            searchRequest.searchOption = options;
            searchRequest.successBlock = resolve;
            searchRequest.errorBlock = reject;
            [self.resultCache setObject:searchRequest forKey:@(poiSearch.hash)];
            NSLog(@"反geo检索发送成功");
        }
        else
        {
            poiSearch.delegate =nil;
            poiSearch =nil;
            reject(@"-1",@"获取经纬度失败",nil);
        }
    }else{
        reject(@"-2",@"传入参数有误",nil);
    }
}

//POI搜索功能 矩形云检索参数信息类
RCT_EXPORT_METHOD(poiSearchNearBy:(BMKPOINearbySearchOption *)options resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
    
    if(options){
        BMKPoiSearch *poiSearch = [BMKPoiSearch new];
        poiSearch.delegate =self;
        BOOL flag = [poiSearch poiSearchNearBy:options];
        
        if(flag)
        {
            SearchRequest *searchRequest = [SearchRequest new];
            searchRequest.searchOption = options;
            searchRequest.successBlock = resolve;
            searchRequest.errorBlock = reject;
            [self.resultCache setObject:searchRequest forKey:@(poiSearch.hash)];
            NSLog(@"反geo检索发送成功");
        }
        else
        {
            poiSearch.delegate =nil;
            poiSearch =nil;
            reject(@"-1",@"获取经纬度失败",nil);
        }
    }else{
        reject(@"-2",@"传入参数有误",nil);
    }
}

#pragma mark -- BMKGeoCodeSearchDelegate
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeSearchResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSInteger searcherHash =searcher.hash;
    SearchRequest *requestItem = [self.resultCache objectForKey:@(searcherHash)];
    if(requestItem){
        
        //NSString *showmeg = [NSString stringWithFormat:@"纬度:%f,经度:%f",result.location.latitude,result.location.longitude];
        
        switch (error) {
            case BMK_SEARCH_NO_ERROR:
                requestItem.successBlock(@{@"address":[(BMKGeoCodeSearchOption *)requestItem.searchOption address],
                                           @"location":@{
                                                   @"latitude": @(result.location.latitude),
                                                   @"longitude": @(result.location.longitude),
                                                   }});
                
                break;
            case BMK_SEARCH_AMBIGUOUS_KEYWORD:
                requestItem.errorBlock(@(BMK_SEARCH_AMBIGUOUS_KEYWORD).stringValue,@"检索词有岐义",nil);
                break;
            case BMK_SEARCH_AMBIGUOUS_ROURE_ADDR:
                requestItem.errorBlock(@(BMK_SEARCH_AMBIGUOUS_ROURE_ADDR).stringValue,@"检索地址有岐义",nil);
                break;
            case BMK_SEARCH_NOT_SUPPORT_BUS:
                requestItem.errorBlock(@(BMK_SEARCH_NOT_SUPPORT_BUS).stringValue,@"该城市不支持公交搜索",nil);
                break;
            case BMK_SEARCH_NOT_SUPPORT_BUS_2CITY:
                requestItem.errorBlock(@(BMK_SEARCH_NOT_SUPPORT_BUS_2CITY).stringValue,@"不支持跨城市公交",nil);
                break;
            case BMK_SEARCH_RESULT_NOT_FOUND:
                requestItem.errorBlock(@(BMK_SEARCH_RESULT_NOT_FOUND).stringValue,@"没有找到检索结果",nil);
                break;
            case BMK_SEARCH_ST_EN_TOO_NEAR:
                requestItem.errorBlock(@(BMK_SEARCH_RESULT_NOT_FOUND).stringValue,@"起终点太近",nil);
                break;
            case BMK_SEARCH_KEY_ERROR:
                requestItem.errorBlock(@(BMK_SEARCH_KEY_ERROR).stringValue,@"key错误",nil);
                break;
            case BMK_SEARCH_NETWOKR_ERROR:
                requestItem.errorBlock(@(BMK_SEARCH_NETWOKR_ERROR).stringValue,@"网络连接错误",nil);
                break;
            case BMK_SEARCH_NETWOKR_TIMEOUT:
                requestItem.errorBlock(@(BMK_SEARCH_NETWOKR_TIMEOUT).stringValue,@"网络连接超时",nil);
                break;
            case BMK_SEARCH_PERMISSION_UNFINISHED:
                requestItem.errorBlock(@(BMK_SEARCH_PERMISSION_UNFINISHED).stringValue,@"还未完成鉴权，请在鉴权通过后重试",nil);
                break;
            case BMK_SEARCH_INDOOR_ID_ERROR:
                requestItem.errorBlock(@(BMK_SEARCH_INDOOR_ID_ERROR).stringValue,@"室内图ID错误",nil);
                break;
            case BMK_SEARCH_FLOOR_ERROR:
                requestItem.errorBlock(@(BMK_SEARCH_FLOOR_ERROR).stringValue,@"室内图检索楼层错误",nil);
                break;
                
            default:
                break;
        }
        
    }
    searcher.delegate =nil;
    [self.resultCache removeObjectForKey:@(searcherHash)];
}

-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeSearchResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSInteger searcherHash = searcher.hash;
    SearchRequest *requestItem = [self.resultCache objectForKey:@(searcherHash)];
    if(requestItem){
        
        //NSString *showmeg = [NSString stringWithFormat:@"纬度:%f,经度:%f",result.location.latitude,result.location.longitude];
        /*
         /// 街道号码
         @property (nonatomic, strong) NSString* streetNumber;
         /// 街道名称
         @property (nonatomic, strong) NSString* streetName;
         /// 区县名称
         @property (nonatomic, strong) NSString* district;
         /// 城市名称
         @property (nonatomic, strong) NSString* city;
         /// 省份名称
         @property (nonatomic, strong) NSString* province;
         */
        
        switch (error) {
            case BMK_SEARCH_NO_ERROR:
                requestItem.successBlock(@{@"address":result.address,
                                           @"location":@{
                                                   @"latitude": @(result.location.latitude),
                                                   @"longitude": @(result.location.longitude),
                                                   },
                                           @"addressDetail":@{@"streetNumber":result.addressDetail.streetNumber,
                                                              @"streetName":result.addressDetail.streetName,
                                                              @"district":result.addressDetail.district,
                                                              @"city":result.addressDetail.city,
                                                              @"province":result.addressDetail.province
                                                              }
                                           //,@"poiList":result.poiList
                                           });
                
                break;
            case BMK_SEARCH_AMBIGUOUS_KEYWORD:
                requestItem.errorBlock(@(BMK_SEARCH_AMBIGUOUS_KEYWORD).stringValue,@"检索词有岐义",nil);
                break;
            case BMK_SEARCH_AMBIGUOUS_ROURE_ADDR:
                requestItem.errorBlock(@(BMK_SEARCH_AMBIGUOUS_ROURE_ADDR).stringValue,@"检索地址有岐义",nil);
                break;
            case BMK_SEARCH_NOT_SUPPORT_BUS:
                requestItem.errorBlock(@(BMK_SEARCH_NOT_SUPPORT_BUS).stringValue,@"该城市不支持公交搜索",nil);
                break;
            case BMK_SEARCH_NOT_SUPPORT_BUS_2CITY:
                requestItem.errorBlock(@(BMK_SEARCH_NOT_SUPPORT_BUS_2CITY).stringValue,@"不支持跨城市公交",nil);
                break;
            case BMK_SEARCH_RESULT_NOT_FOUND:
                requestItem.errorBlock(@(BMK_SEARCH_RESULT_NOT_FOUND).stringValue,@"没有找到检索结果",nil);
                break;
            case BMK_SEARCH_ST_EN_TOO_NEAR:
                requestItem.errorBlock(@(BMK_SEARCH_RESULT_NOT_FOUND).stringValue,@"起终点太近",nil);
                break;
            case BMK_SEARCH_KEY_ERROR:
                requestItem.errorBlock(@(BMK_SEARCH_KEY_ERROR).stringValue,@"key错误",nil);
                break;
            case BMK_SEARCH_NETWOKR_ERROR:
                requestItem.errorBlock(@(BMK_SEARCH_NETWOKR_ERROR).stringValue,@"网络连接错误",nil);
                break;
            case BMK_SEARCH_NETWOKR_TIMEOUT:
                requestItem.errorBlock(@(BMK_SEARCH_NETWOKR_TIMEOUT).stringValue,@"网络连接超时",nil);
                break;
            case BMK_SEARCH_PERMISSION_UNFINISHED:
                requestItem.errorBlock(@(BMK_SEARCH_PERMISSION_UNFINISHED).stringValue,@"还未完成鉴权，请在鉴权通过后重试",nil);
                break;
            case BMK_SEARCH_INDOOR_ID_ERROR:
                requestItem.errorBlock(@(BMK_SEARCH_INDOOR_ID_ERROR).stringValue,@"室内图ID错误",nil);
                break;
            case BMK_SEARCH_FLOOR_ERROR:
                requestItem.errorBlock(@(BMK_SEARCH_FLOOR_ERROR).stringValue,@"室内图检索楼层错误",nil);
                break;
                
            default:
                break;
        }
        
    }
    searcher.delegate =nil;
    [self.resultCache removeObjectForKey:@(searcherHash)];
}

#pragma mark --BMKSearchDelegate
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPOISearchResult*)result errorCode:(BMKSearchErrorCode)error
{
    NSInteger searcherHash = searcher.hash;
    SearchRequest *requestItem = [self.resultCache objectForKey:@(searcherHash)];
    if(requestItem){
        
        switch (error) {
            case BMK_SEARCH_NO_ERROR:{
                NSMutableArray *resultList = [NSMutableArray new];
                NSArray *pointList = result.poiInfoList;
                for (int i=0; i < pointList.count; i++) {
                    
                    BMKPoiInfo *pointInfo =  pointList[i];
                    CLLocationCoordinate2D loctaion = pointInfo.pt;
                    NSDictionary *mapRuselt = @{@"name":[self isEmpty:pointInfo.name],@"address":[self isEmpty:pointInfo.address],@"latitude":@(loctaion.latitude)?:@(0),@"longitude":@(loctaion.longitude)?:@(0)};
                    
                    [resultList addObject:mapRuselt];
                }
                if (resultList.count == pointList.count) {
                    
                    requestItem.successBlock(resultList);
                    
                    resultList = nil;
                    
                }
                break;
            }
            case BMK_SEARCH_AMBIGUOUS_KEYWORD:
                requestItem.errorBlock(@(BMK_SEARCH_AMBIGUOUS_KEYWORD).stringValue,@"检索词有岐义",nil);
                break;
            case BMK_SEARCH_AMBIGUOUS_ROURE_ADDR:
                requestItem.errorBlock(@(BMK_SEARCH_AMBIGUOUS_ROURE_ADDR).stringValue,@"检索地址有岐义",nil);
                break;
            case BMK_SEARCH_NOT_SUPPORT_BUS:
                requestItem.errorBlock(@(BMK_SEARCH_NOT_SUPPORT_BUS).stringValue,@"该城市不支持公交搜索",nil);
                break;
            case BMK_SEARCH_NOT_SUPPORT_BUS_2CITY:
                requestItem.errorBlock(@(BMK_SEARCH_NOT_SUPPORT_BUS_2CITY).stringValue,@"不支持跨城市公交",nil);
                break;
            case BMK_SEARCH_RESULT_NOT_FOUND:
                requestItem.errorBlock(@(BMK_SEARCH_RESULT_NOT_FOUND).stringValue,@"没有找到检索结果",nil);
                break;
            case BMK_SEARCH_ST_EN_TOO_NEAR:
                requestItem.errorBlock(@(BMK_SEARCH_RESULT_NOT_FOUND).stringValue,@"起终点太近",nil);
                break;
            case BMK_SEARCH_KEY_ERROR:
                requestItem.errorBlock(@(BMK_SEARCH_KEY_ERROR).stringValue,@"key错误",nil);
                break;
            case BMK_SEARCH_NETWOKR_ERROR:
                requestItem.errorBlock(@(BMK_SEARCH_NETWOKR_ERROR).stringValue,@"网络连接错误",nil);
                break;
            case BMK_SEARCH_NETWOKR_TIMEOUT:
                requestItem.errorBlock(@(BMK_SEARCH_NETWOKR_TIMEOUT).stringValue,@"网络连接超时",nil);
                break;
            case BMK_SEARCH_PERMISSION_UNFINISHED:
                requestItem.errorBlock(@(BMK_SEARCH_PERMISSION_UNFINISHED).stringValue,@"还未完成鉴权，请在鉴权通过后重试",nil);
                break;
            case BMK_SEARCH_INDOOR_ID_ERROR:
                requestItem.errorBlock(@(BMK_SEARCH_INDOOR_ID_ERROR).stringValue,@"室内图ID错误",nil);
                break;
            case BMK_SEARCH_FLOOR_ERROR:
                requestItem.errorBlock(@(BMK_SEARCH_FLOOR_ERROR).stringValue,@"室内图检索楼层错误",nil);
                break;
            default:
                break;
        }
    }
    searcher.delegate =nil;
    [self.resultCache removeObjectForKey:@(searcherHash)];
    
}

- (NSString*)isEmpty:(NSString *)string
{
    if(string == nil || string == NULL){
        return @"";
    }else{
        return [NSString stringWithFormat:@"%@",string];
    }
}
@end
